const { join } = require('path');
const colors = require('colors');
const EventEmitter = require('events');
const execa = require('execa');
class MyEmitter extends EventEmitter { }
const myEmitter = new MyEmitter();

const {
	gitClone,
	getConfig,
	setDependencies,
	getPkg
} = require('./utils');
const projectCwd = process.cwd();

async function install(moduleName) {

	const rule = getConfig('rule');
	const pkg = getConfig('pkg');
	const gitUrl = pkg[moduleName] ? pkg[moduleName] : rule.replace('[name]', moduleName);
	const moduleDir = join(projectCwd, `node_modules/${moduleName}`);
	const pkgDir = join(moduleDir, 'package.json');

	let res = await gitClone(gitUrl, moduleDir);

	if (res.status === 0) {
		setDependencies(moduleName, '0.0.0');

		console.log(colors.green(`Module ${moduleName} is installed`));
	} else {
		execa('npm', ['install', ...process.argv.slice(2)]);
	}

	myEmitter.emit('event', moduleName);
}

module.exports = function ({ args }) {
	const moduleName = args[0];

	if (moduleName) {
		install(moduleName);
	}
	else {
		const wbdependencies = getPkg('WBDependencies');
		const modulelist = Object.keys(wbdependencies);

		let count = 0;

		myEmitter.on('event', (modulename) => {
			count++;
			if (modulelist[count]) {
				install(modulelist[count]);
			}
			else {
				execa('npm', ['install', ...process.argv.slice(2)]);
			}
		});

		install(modulelist[count]);
	}
};